package cn.net.shuxing.yifu.common.front.controller;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.*;
import cn.net.shuxing.yifu.common.dto.BankCardReq;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.dto.CashDealRecordDto;
import cn.net.shuxing.yifu.common.service.*;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.RedisKeyCreator;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import cn.net.shuxing.yifu.common.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/front/my/wallet")
public class MyWalletController extends BaseController {

    @Autowired
    private UserCashHistoryService userCashHistoryService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private ShareholderWalletService shareholderWalletService;

    @Autowired
    private UserBankCardService userBankCardService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCapitalService userCapitalService;

    @Autowired
    private UserDealHistoryService userDealHistoryService;

    @Autowired
    private FrontCommonService frontCommonService;

    @Autowired
    private DealParamService dealParamService;

    @Autowired
    private CashWalletService cashWalletService;

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private CoinTypeService coinTypeService;

    @Autowired
    private DealController dealController;

    @Autowired
    private RechargeHistoryService rechargeHistoryService;

    @Autowired
    private UserWithdrawalCashService userWithdrawalCashService;

    @Autowired
    private UserTransferService userTransferService;

    @Autowired
    private OpenPriceHistoryService openPriceHistoryService;

    @Autowired
    private ShareholderBuyGrantHistoryService shareholderBuyGrantHistoryService;

    @Autowired
    private ShortService shortService;


    @ApiOperation(value = "获取钱包信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping("/info")
    public BaseDto getWalletInfo(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null)
            return baseDto;

        User user = userService.getByPrimaryKey(userId);
        if (user.getType() == UserType.MEMBER) {
            MemberWallet memberWallet = memberWalletService.getByMemberId(userId);
            BaseDto baseDto1 = new BaseDto();
            baseDto1.setData(memberWallet);
            return baseDto1;
        }

        if (user.getType() == UserType.SHAREHOLDER) {
            ShareholderWallet shareholderWallet = shareholderWalletService.getByShareholderId(userId);
            BaseDto baseDto1 = new BaseDto();
            baseDto1.setData(shareholderWallet);
            return baseDto1;
        } else {
            return BaseDto.error("暂时只支持会员(1)和股东(2)钱包");
        }
    }

    /**
     * 获取钱包所有币种信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/info/coin/all")
    public BaseDto getWalletAllCoinInfo(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        Map<String, Object> map = new HashMap<>();
        List<CoinType> coinTypeList = coinTypeService.getAllWithoutComplete();
        List<Object> list = new ArrayList<>();

        Integer type = userService.getByPrimaryKeyWithoutComplete(userId).getType();

        for (CoinType coinType : coinTypeList) {
            Integer coinTypeId = coinType.getId();
            BaseDto dealRecord = getDealRecord(userId, coinTypeId, 1, 10);
            BaseDto walletCoinInfo = getWalletCoinInfo(userId, coinTypeId);
            Map<String, Object> map1 = new HashMap<>();
            if (walletCoinInfo == null)
                continue;
            BigDecimal totalGrantCount = null;
            if (type == UserType.SHAREHOLDER) {
                totalGrantCount = shareholderBuyGrantHistoryService.getTotalGrantCount(userId, coinTypeId);
            }
            map1.put("coinInfoToCNY", walletCoinInfo.getData());
            map1.put("coinInfoDealRecord", dealRecord.getData());
            map1.put("simpleName", coinType.getSimpleName());
            map1.put("name", coinType.getName());
            map1.put("coinTypeId", coinTypeId);
            map1.put("totalGrantCount", totalGrantCount);
            list.add(map1);

        }

        BaseDto capitalToCNY = getCapitalToCNY(userId);
        map.put("toCNY", capitalToCNY.getData());
        map.put("coinInfo", list);

        /** 现金钱包部分 **/
        CashWallet cashWallet = cashWalletService.getByPrimaryKey(userId);
        if (cashWallet != null) {
            map.put("cashCount", cashWallet.getCashCount());
        }


//        List<BaseBean> list1 = new ArrayList<>();
//        PageHelper.startPage(1, 10);
//        List<UserDealHistory> hangBuyAndHangSaleByUserId = userDealHistoryService.getHangBuyAndHangSaleByUserId(userId);
//        PageInfo<UserDealHistory> userDealHistoryPageInfo1 = new PageInfo<>(hangBuyAndHangSaleByUserId);
//        list1.addAll(userDealHistoryPageInfo1.getList());
//
//        BaseDto rechargeHistory = getRechargeHistory(userId, 1, 10);
//        list1.addAll((Collection<? extends BaseBean>) rechargeHistory.getData());
//
//        BaseDto userWitdrawCashList = getUserWitdrawCashList(userId, 1, 10);
//        list1.addAll((Collection<? extends BaseBean>) userWitdrawCashList.getData());
//        list1.sort((x, y) -> {
//            return y.getCreateTime().compareTo(x.getCreateTime());
//        });

        map.put("cashDealRecord", userCashHistoryService.getsByUserIdCash(userId, 1, 10));
        return BaseDto.ok(map);

        /*
            {
                #总资产折合
                toCNY:{
                    totalCount: 总资产折合
                    usableCount: 可用资产折合
                    frozenCount: 冻结资产折合
                    },
                #各个币种对应的信息
                coinInfo:[
                    {
                        simpleName: 币种简称,
                        name: 币种名称
                        # 币种资产信息
                        coinInfoToCNY:{
                                usableCount: 可用资产,
                                frozenCount: 冻结资产,
                                toCNY:       折合
                            },
                        # 币种交易记录
                        coinInfoDealRecord:[
                            {
                            	id:主键,
                            	userId:用户id,
                            	dealType:交易类型，0为挂买，1为挂卖，2位转账收入，3位转账支出，4位转账手续费,
                            	dealScene:交易场景，0为挂买，1为挂卖，2位股东转账，3位会员转账，4位系统回购，5位商户转交易钱包，6为用户购买,
                            	coinTypeId:币种id,
                            	singlePrice:单价,
                            	dealAliveCoinCount:交易活币数量,
                            	deleted:是否已被删除，0表示未被删除，1表示已被删除,
                            	createTime:创建时间,
                            	updateTime:最新修改时间
                            }
                        ]
                    }
                ],
                cashCount: 现金总额,
                #现金交易记录
                cashDealRecord:[
                    {
                        dealTypeName: 交易类型
                        ...
                    }
                ]
            }
         */
    }

    public BaseDto getUserWitdrawCashList(Integer userId,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<UserWithdrawalCash> userWithdrawalCashPageInfo = new PageInfo<>(userWithdrawalCashService.getsByUserId(userId));
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userWithdrawalCashPageInfo.getList());
        return baseDto;
    }

    @RequestMapping("/info/coin")
    public BaseDto getWalletCoinInfo(Integer userId, Integer coinTypeId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeId(userId, coinTypeId);
        if (userCapital == null) {
            return BaseDto.ok(null);
        }
        Map<String, BigDecimal> map = new HashMap<>();
        Integer state = userService.getByPrimaryKey(userId).getState();

        String value = dealParamService.getValue(userId, coinTypeId, UserParamConst.MEMBER_KEEP_ALIVE_COIN_MIN_COUNT);
        if (state == UserState.FROZEN) {
            map.put("usableCount", new BigDecimal(0));
            map.put("frozenCount", userCapital.getAliveCoinCount().add(userCapital.getSleepCoinCount()));
        } else {
            if (userCapital.getType() == UserType.SHAREHOLDER) {
                map.put("usableCount", userCapital.getAliveCoinCount());
                map.put("frozenCount", userCapital.getSleepCoinCount());

            } else {
                BigDecimal frozenCount = new BigDecimal(value);
//                /** 获取坐空权限 **/
//                Integer userShortCount = shortService.getUserShortCount(userId, coinTypeId);
//                if (userShortCount <= 0) {
//                    if (StringUtils.hasText(value)) {
//                        frozenCount = new BigDecimal(value);
//                    }
//                }else {
//                    frozenCount =
//                }

                BigDecimal ssssss = userCapital.getAliveCoinCount().subtract(frozenCount);
                map.put("usableCount", ssssss);
                map.put("frozenCount", frozenCount.add(userCapital.getSleepCoinCount()));
            }


        }
        //Jedis //jedis = jedisUtil.getJedis();
        String s = jedisUtil.get(RedisKeyCreator.openPrice(coinTypeId));
        //jedisUtil.close();
        BigDecimal openPrice = new BigDecimal(0);
        if (StringUtils.hasText(s))
            openPrice = new BigDecimal(s);
        BigDecimal ethValue = userCapital.getAliveCoinCount().add(userCapital.getSleepCoinCount());
//        String ethExchangeRate = jedisUtil.get(RedisKeyCreator.ethExchangeRate());
//        if (!StringUtils.hasText(ethExchangeRate)) {
//            ethExchangeRate = "1690";
//        }

        map.put("toCNY", ethValue.multiply(openPriceHistoryService.getByCoinTypeId(1)));
        return BaseDto.ok(map);

        /*
            {
                usableCount: 可用资产,
                frozenCount: 冻结资产,
                toCNY:       折合
            }
         */
    }

    /**
     * 获取交易钱包信息
     *
     * @param userId     用户id
     * @param coinTypeId 币种id
     * @return
     */
    @RequestMapping("/info/deal")
    public BaseDto getDealWalletInfo(Integer userId, Integer coinTypeId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        Integer type = userService.getByPrimaryKey(userId).getType();
        UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinTypeId, type);
        return BaseDto.ok(userCapital);
    }

    /**
     * 获取本月转账量
     *
     * @param userId     用户id
     * @param coinTypeId 币种id
     * @return
     */
    @RequestMapping("/info/transfer/thisMonth")
    public BaseDto getThisMonthTransferCount(Integer userId, Integer coinTypeId) {
        BigDecimal count = userDealHistoryService.getThisMonthTransferCount(userId, coinTypeId);
        return BaseDto.ok(count);
    }

    /** 新增 **/
    /**
     * 获取默认银行卡
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/bankcard/default")
    public BaseDto getDefaultBankCard(Integer userId) {
        UserBankCard defaultBankCard = userBankCardService.getDefaultBankCard(userId);
        if (defaultBankCard == null)
            return BaseDto.ok(null);
        String bankCardNum = defaultBankCard.getBankCardNum();
        bankCardNum = bankCardNum.substring(0, 4) + "****" + bankCardNum.substring(bankCardNum.length() - 4);
        ;
        defaultBankCard.setBankCardNum(bankCardNum);
        return BaseDto.ok(defaultBankCard);
    }

    /** 新增 **/
    /**
     * 设置默认银行卡
     *
     * @param userId         用户id
     * @param userBankCardId 用户银行卡对象(UserBankCard对象)的id属性,不是银行卡号
     * @return
     */
    @RequestMapping("/bankcard/default/set")
    public BaseDto setDefaultBankCard(Integer userId, Integer userBankCardId) {
        boolean flag = userBankCardService.setBankCardDefault(userId, userBankCardId);
        if (flag)
            return BaseDto.ok("设置成功");
        else
            return BaseDto.error("该银行卡不存在或未与该用户绑定");
    }

    /** 新增 **/
    /**
     * 获取该用户绑定的所有银行卡
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/bankcard/all")
    public BaseDto getAllBankCardByUserId(Integer userId) {
        List<UserBankCard> userBankCards = userBankCardService.getsByUserId(userId);
        for (UserBankCard userBankCard : userBankCards) {
            userBankCard.setIdCardNum(null);
            String bankCardNum = userBankCard.getBankCardNum();
            bankCardNum = bankCardNum.substring(0, 4) + "****" + bankCardNum.substring(bankCardNum.length() - 4);
            ;
            userBankCard.setBankCardNum(bankCardNum);
        }
        return BaseDto.ok(userBankCards);
    }

    /** 新增 **/
    /**
     * 绑定新银行卡
     * <p>
     * //     * @param userId         用户id
     * //     * @param holderName     持卡人姓名
     * //     * @param idCardNum      身份证号
     * //     * @param bankCardNum    银行卡号
     * //     * @param openBank       开户银行
     * //     * @param openBankBranch 开户支行
     * //     * @param phoneNum       手机号
     *
     * @return
     */
    @RequestMapping(value = "/bankcard/bind")
    public BaseDto bindBankCard(@ModelAttribute BankCardReq bankCardReq) throws UnsupportedEncodingException {
        boolean flag = frontCommonService.isTrueInfoVerified(bankCardReq.getUserId());
        if (!flag)
            return BaseDto.error("请先完成实名认证");
        flag = userBankCardService.bindable(bankCardReq.getBankCardNum());
        if (!flag)
            return BaseDto.error("此银行卡已被绑定");
        UserBankCard userBankCard = new UserBankCard();
        userBankCard.setUserId(bankCardReq.getUserId());
        userBankCard.setIdCardNum(bankCardReq.getIdCardNum());
        userBankCard.setBankCardNum(bankCardReq.getBankCardNum());
//        字符串编码格式问题，线上部署的时候必须得这样，本地测试的时候改回原来模样
        userBankCard.setHolderName(bankCardReq.getHolderName());
        userBankCard.setOpenBank(bankCardReq.getOpenBank());
        userBankCard.setOpenBankBranch(bankCardReq.getOpenBankBranch());
        userBankCard.setPhoneNum(bankCardReq.getPhoneNum());
        userBankCard.setValidityTerm(bankCardReq.getValidityTerm());
        System.out.println("绑定新银行卡接口传入的参数:" + JSON.toJSONString(userBankCard));

        boolean verify = userBankCardService.verify(userBankCard);
        if (!verify) {
            return BaseDto.error("银行卡信息输入错误");
        }
        userBankCardService.insert(userBankCard);

        return BaseDto.ok("绑定完成");
    }

    /**
     * 解绑银行卡
     *
     * @param userId
     * @param userBankCardId
     * @return
     */
    @RequestMapping("/bankcard/unbind")
    public BaseDto bindBankCard(Integer userId, Integer userBankCardId) {
        boolean flag = frontCommonService.isTrueInfoVerified(userId);
        if (!flag)
            return BaseDto.error("请先完成实名认证");
        UserBankCard userBankCard1 = userBankCardService.getByPrimaryKey(userBankCardId);
        if (userBankCard1 == null)
            return BaseDto.error("此银行卡不存在");
        if (userBankCard1.getUserId() != userId)
            return BaseDto.error("您未绑定此银行卡");

        userBankCardService.delete(userBankCardId);
        return BaseDto.ok("解定完成");
    }

    /**
     * 获取提现手续费率
     *
     * @return
     */
    @RequestMapping("/withdraw/fee")
    public BaseDto getWithdrawFee() {
        //Jedis //jedis = jedisUtil.getJedis();
        String userWithdraw = jedisUtil.get(RedisKeyCreator.userWithdrawFeeRatio());
        return BaseDto.ok(userWithdraw);
    }

    /**
     * 获取资产折合
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/toCNY")
    public BaseDto getCapitalToCNY(Integer userId) {
        List<CoinType> coinTypeList = coinTypeService.getAllWithoutComplete();

        /** 总折合 **/
        BigDecimal totalCount = new BigDecimal(0);
        /** 可用折合 **/
        BigDecimal usableCount = new BigDecimal(0);
        /** 冻结资产**/
        //Jedis //jedis = jedisUtil.getJedis();

        for (CoinType coinType : coinTypeList) {
            Integer coinTypeId = coinType.getId();
            BigDecimal openPrice = openPriceHistoryService.getOpenPrice(coinTypeId);
            UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeId(userId, coinTypeId);
            if (userCapital != null) {
                BigDecimal aliveCoinCount = userCapital.getAliveCoinCount();
                totalCount = totalCount.add(aliveCoinCount.multiply(openPrice));
                BigDecimal sleepCoinCount = userCapital.getSleepCoinCount();
                totalCount = totalCount.add(sleepCoinCount.multiply(openPrice));
            }
            BaseDto baseDto = dealController.getUserableCoinCount(userId, coinTypeId);
            BigDecimal memberKeepMinCount = new BigDecimal(jedisUtil.get(RedisKeyCreator.memberKeepAliveCoinMinCount()));
            if (!baseDto.isError()) {
                BigDecimal usableCoinCount = (BigDecimal) baseDto.getData();
                if (usableCoinCount != null) {
                    usableCount = usableCount.add(usableCoinCount.multiply(openPrice));
                }
            }
        }

        BigDecimal cashCount = new BigDecimal(0);
        CashWallet cashWallet = cashWalletService.getByPrimaryKey(userId);
        if (cashWallet != null) {
            cashCount = cashWallet.getCashCount();
        }

        totalCount = totalCount.add(cashCount);
        usableCount = usableCount.add(cashCount);
        Map<String, BigDecimal> map = new HashMap<>();

        map.put("totalCount", totalCount);
        map.put("usableCount", usableCount);
        map.put("frozenCount", totalCount.subtract(usableCount));
        return BaseDto.ok(map);

        /*
           {
                totalCount: 总资产折合
                usableCount: 可用资产折合
                frozenCount: 冻结资产折合
           }
         */
    }

    public BaseDto getCapitalToCNY(Integer userId, int role) {
        List<CoinType> coinTypeList = coinTypeService.getAllWithoutComplete();

        /** 总折合 **/
        BigDecimal totalCount = new BigDecimal(0);
        /** 可用折合 **/
        BigDecimal usableCount = new BigDecimal(0);
        /** 冻结资产**/
        //Jedis //jedis = jedisUtil.getJedis();

        for (CoinType coinType : coinTypeList) {
            Integer coinTypeId = coinType.getId();
            String openPriceStr = jedisUtil.get(RedisKeyCreator.openPrice(coinTypeId));
            BigDecimal openPrice = null;
            if (!StringUtils.hasText(openPriceStr))
                openPrice = new BigDecimal(0);
            else
                openPrice = new BigDecimal(openPriceStr);
            UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinTypeId, role);
            if (userCapital != null) {
                BigDecimal aliveCoinCount = userCapital.getAliveCoinCount();
                totalCount = totalCount.add(aliveCoinCount.multiply(openPrice));
                BigDecimal sleepCoinCount = userCapital.getSleepCoinCount();
                totalCount = totalCount.add(sleepCoinCount.multiply(openPrice));
            }
            BaseDto baseDto = dealController.getUserableCoinCount(userId, coinTypeId);
            if (!baseDto.isError()) {
                BigDecimal usableCoinCount = (BigDecimal) baseDto.getData();
                if (usableCoinCount != null)
                    usableCount = usableCount.add(usableCoinCount);
            }
        }

        BigDecimal cashCount = cashWalletService.getByPrimaryKey(userId).getCashCount();
        totalCount = totalCount.add(cashCount);
        usableCount = usableCount.add(cashCount);

        Map<String, BigDecimal> map = new HashMap<>();

        map.put("totalCount", totalCount);
        map.put("usableCount", usableCount);

        map.put("frozenCount", totalCount.subtract(usableCount));
        return BaseDto.ok(map);

        /*
           {
                totalCount: 总资产折合
                usableCount: 可用资产折合
                frozenCount: 冻结资产折合
           }
         */
    }

    @RequestMapping("/deal/info/record")
    public BaseDto getDealRecord(Integer userId,
                                 @RequestParam(value = "coinTypeId", defaultValue = "1") Integer coinTypeId,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        List<UserDealHistory> userDealHistoryList = userDealHistoryService.getAllDealByUserIdAndCoinTypeId(userId, coinTypeId, pageNum, pageSize);
        for (UserDealHistory userDealHistory : userDealHistoryList) {
            BigDecimal dealCount = userDealHistory.getDealAliveCoinCount();
            String dealTypeName = "";
            if (userDealHistory.getDealType() == DealType.HANG_BUY) {
                dealTypeName = "挂买收入";
            }
            if (userDealHistory.getDealType() == DealType.HANG_SALE) {
                dealCount = new BigDecimal(0).subtract(dealCount);
                dealTypeName = "挂卖支出";
            }
            if (userDealHistory.getDealType() == DealType.TRANSFER_IN) {
                dealTypeName = "转账收入";
            }
            if (userDealHistory.getDealType() == DealType.TRANSFER_OUT) {
                dealCount = new BigDecimal(0).subtract(dealCount);
                dealTypeName = "转账支出";
            }
            if (userDealHistory.getDealType() == DealType.SYS_BUY_BACK) {
                dealCount = new BigDecimal(0).subtract(dealCount);
                dealTypeName = "回购支出";
            }
            if (userDealHistory.getDealType() == DealType.FEE) {
                dealCount = new BigDecimal(0).subtract(dealCount);
                dealTypeName = "手续费";
            }
            if (userDealHistory.getDealType() == DealType.BUY_COIN_GRANT) {
                dealCount = new BigDecimal(0).subtract(dealCount);
                dealTypeName = "购买配币";
            }
            if (userDealHistory.getDealType() == DealType.HANG_SALE_CANSEL) {
                dealTypeName = "撤挂卖单退款";
            }
            userDealHistory.setDealAliveCoinCount(dealCount);
            userDealHistory.setDealTypeName(dealTypeName);
        }
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userDealHistoryList);
        return baseDto;
    }


    @RequestMapping("/recharge/all")
    public BaseDto getRechargeHistory(Integer userId,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RechargeHistory> rechargeHistories = rechargeHistoryService.getsByUserId(userId);
        PageInfo<RechargeHistory> rechargeHistoryPageInfo = new PageInfo<>(rechargeHistories);
        return BaseDto.ok(rechargeHistoryPageInfo.getList());
    }


    @RequestMapping("/transferIn/all")
    public BaseDto getTransferInRecords(Integer userId,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserTransfer> userTransferList = userTransferService.getByUserIdAndDealType(userId, DealType.TRANSFER_IN);
        PageInfo<UserTransfer> userTransferPageInfo = new PageInfo<>(userTransferList);
        return BaseDto.ok(userTransferPageInfo.getList());
    }


    /**
     * 已提现金额
     *
     * @param userId
     * @return
     */
    @RequestMapping("/withdraw/overCount")
    public BaseDto getHasWithdrawCount(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        List<UserWithdrawalCash> userWithdrawalCashes = userWithdrawalCashService.getsByUserIdAndState(userId, UserWithdrawalState.COMPLETED);
        if (userWithdrawalCashes == null || userWithdrawalCashes.isEmpty())
            return BaseDto.ok(new BigDecimal(0));
        BigDecimal count = new BigDecimal(0);
        for (UserWithdrawalCash userWithdrawalCash : userWithdrawalCashes) {
            count = count.add(new BigDecimal(userWithdrawalCash.getFactMoney()).divide(new BigDecimal(100), 8, BigDecimal.ROUND_HALF_UP));
        }
        return BaseDto.ok(count);
    }

    /**
     * 获取现金交易记录
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
//    @RequestMapping("/cash/dealRecord")
//    public BaseDto getCashDeaLRecords(Integer userId,
//                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
//                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
//        BaseDto baseDto = new BaseDto();
//        List<CashDealRecordDto> cashDealRecordDtos = new ArrayList<>();
//        PageHelper.startPage(pageNum, pageSize);
//        List<UserDealHistory> hangBuyAndHangSaleByUserId = userDealHistoryService.getHangBuyAndHangSaleByUserId(userId);
//        if (hangBuyAndHangSaleByUserId != null) {
//            for (UserDealHistory userDealHistory : hangBuyAndHangSaleByUserId) {
//                cashDealRecordDtos.add(userDealHistory.toCashDealRecordDto());
//            }
//        }
//        List<RechargeHistory> rechargeHistories = rechargeHistoryService.getsByUserIdAndPaymentStatus(userId, PaymentStatus.PAID);
//        if (rechargeHistories != null) {
//            for (RechargeHistory rechargeHistory : rechargeHistories) {
//                cashDealRecordDtos.add(rechargeHistory.toCashDealRecordDto());
//            }
//        }
//
//        List<UserWithdrawalCash> userWithdrawalCashes = userWithdrawalCashService.getsByUserId(userId);
//        if (userWithdrawalCashes != null) {
//            for (UserWithdrawalCash userWithdrawalCash : userWithdrawalCashes) {
//                cashDealRecordDtos.add(userWithdrawalCash.toCashDealRecordDto());
//            }
//        }
//
//        cashDealRecordDtos.sort((x, y) -> {
//            return y.getCreateTime().compareTo(x.getCreateTime());
//        });
//
//        baseDto.setCode(0);
//        baseDto.setData(new PageInfo<>(cashDealRecordDtos));
//        return baseDto;
//    }
    @RequestMapping("/cash/dealRecord")
    public BaseDto getCashDeaLRecords(Integer userId,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        BaseDto baseDto = new BaseDto();
        List<CashDealRecordDto> cashDealRecordDtos = userCashHistoryService.getsByUserId(userId, pageNum, pageSize);
        baseDto.setData(cashDealRecordDtos);
        baseDto.setCode(0);
        return baseDto;
    }

    @RequestMapping("/cash/info")
    public BaseDto getCashWalletInfo(Integer userId) {
        BaseDto baseDto = checkUserId(userId);
        if (baseDto != null && baseDto.isError())
            return baseDto;
        CashWallet cashWallet = cashWalletService.getByPrimaryKey(userId);
        //Jedis //jedis = jedisUtil.getJedis();
        BigDecimal byCoinTypeId = openPriceHistoryService.getByCoinTypeId(1);
        BigDecimal totalCount = cashWallet.getCashCount();
        BigDecimal toYF = new BigDecimal(0);
        toYF = totalCount.divide(byCoinTypeId, 8, BigDecimal.ROUND_HALF_UP);
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", totalCount);
        map.put("toYF", toYF);
        return BaseDto.ok(map);

        /*
        {
            totalCount: 当前可用
            toYF: 资产折合(YF)
        }
         */
    }

    ///front/my/wallet

    /**
     * 获取挂买挂卖时显示可用金额
     *
     * @param userId
     * @param type
     * @param coinTypeId
     * @return
     */
    @RequestMapping("/useAbleCount")
    public BaseDto getUseAbleCount(Integer userId,
                                   Integer type,
                                   Integer coinTypeId) {
        BigDecimal useAbleCount = new BigDecimal(0);
        BaseDto baseDto = new BaseDto();
        if (type == DealType.HANG_BUY) {
            CashWallet cashWallet = cashWalletService.getByUserId(userId);
            useAbleCount = cashWallet.getCashCount();
        }

        if (type == DealType.HANG_SALE) {
            User user = userService.getByPrimaryKey(userId);
            Integer state = user.getState();

            if (state == UserState.OK) {
                UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinTypeId, user.getType());
                BigDecimal aliveCoinCount = userCapital.getAliveCoinCount();
                BigDecimal minCount = new BigDecimal(jedisUtil.get(RedisKeyCreator.memberKeepAliveCoinMinCount()));
//                BigDecimal minCount = new BigDecimal(dealParamService.getValue(userId, coinTypeId, "dealWalletMinCount"));
                useAbleCount = aliveCoinCount.subtract(minCount);
                if (useAbleCount.compareTo(new BigDecimal(0)) <= 0) {
                    return BaseDto.ok(useAbleCount);
                }
            }
        }

        baseDto.setData(useAbleCount);
        baseDto.setCode(0);
        return baseDto;
    }

    @RequestMapping("/capitalWalletState")
    public BaseDto getCapitalState(Integer userId) {
        User user = userService.getByPrimaryKeyWithoutComplete(userId);
        Integer type = user.getType();
        if (type == UserType.MEMBER) {
            List<UserCapital> userCapitals = userCapitalService.getsByUserIdAndUserType(userId, type);
            if (userCapitals != null && !userCapitals.isEmpty()) {
                for (UserCapital userCapital : userCapitals) {
                    Integer state = userCapital.getState();
                    return BaseDto.ok(state);
                }
            }
        }

        if (type == UserType.NONE) {
            return BaseDto.ok(3);
        }

        if (type == UserType.SHAREHOLDER) {
            UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, 1, type);
            if (userCapital == null) {
                return BaseDto.ok("账户异常");
            } else {
                return BaseDto.ok(userCapital.getState());
            }
        }

        return BaseDto.ok("账户异常");
    }

    /**
     * 用户解冻
     *
     * @param userId
     * @return
     */
    @RequestMapping("/unfrozen")
    public BaseDto Unfrozen(Integer userId) {
        User user = userService.getByPrimaryKeyWithoutComplete(userId);
        if (user.getState().equals(UserState.FROZEN)) {
            return BaseDto.error("用户当前不需要解冻");
        }
        UserRole userRole = userRoleService.getByUserIdAndUserRole(userId, user.getType());
        userRole.setState(4);
        userRoleService.update(userRole);
        return BaseDto.ok("申请解冻成功");
//        return userWalletFrozeService.unFrozenUser(userId, userService.getByPrimaryKeyWithoutComplete(userId).getType());
    }
}
